/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.staffs.student.autopilot;

import java.io.IOException;

import org.apache.log4j.Logger;

import uk.ac.staffs.student.autopilot.packet.PacketBuilder;

/**
 * 
 * @author Peter
 */
public class SerialPortManagerMock implements Runnable {

    private PacketBuilder packetBuilder;
    public static Logger logger = Logger.getLogger(SerialPortManagerMock.class);
    /**
     * The port we're normally going to use.
     */
    private static final String PORT_NAMES[] = { "COM2", // Windows
            "COM3", // Windows
            "COM4", // Windows
            "COM5", // Windows
            "COM6", // Windows
            "COM7", // Windows
    };

    /**
     * Milliseconds to block while waiting for port open
     */
    private static final int TIME_OUT = 2000;
    /**
     * Default bits per second for COM port.
     */
    private static final int DATA_RATE = 19200;

    /**
     * 
     */

    public SerialPortManagerMock() {
    }

    @Override
    public void run() {
        this.initialize();

    }

    protected PacketBuilder initialize() {

        // packetBuilder = new PacketBuilder(this);

        SerialPortMock serialPort;
        try {
            serialPort = new SerialPortMock(packetBuilder);
            // open the streams
            getPacketBuilder().setInput(serialPort.getInputStream());
            getPacketBuilder().setOutput(serialPort.getOutputStream());
            final Thread serPortThread = new Thread(serialPort);
            serPortThread.start();

            while (!Thread.interrupted()) {
                serPortThread.join();

            }
            serPortThread.interrupt();
        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (final InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // add event listeners
        // serialPort.addEventListener(getPacketBuilder());
        // serialPort.notifyOnDataAvailable(true);

        logger.info("Opened serial port: " + "Mock Serial Port (COM3)");

        return getPacketBuilder();
    }

    /**
     * This should be called when you stop using the port. This will prevent
     * port locking on platforms like Linux.
     */
    public synchronized void close() {
    }

    /**
     * @return the packetBuilder
     */
    public PacketBuilder getPacketBuilder() {
        return packetBuilder;
    }

}
